package com.aspire.boc.mms.gwcmp.action;

import java.io.File;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.aspire.boc.mms.gwcmp.dao.GwcmpBlacklistMapper;
import com.aspire.boc.mms.gwcmp.dao.GwcmpProcessTaskMapper;
import com.aspire.boc.mms.gwcmp.dao.GwcmpTableUpdateInfoMapper;
import com.aspire.boc.mms.gwcmp.model.GwcmpBlacklist;
import com.aspire.boc.mms.gwcmp.model.GwcmpBlacklistExample;
import com.aspire.boc.mms.gwcmp.model.GwcmpProcessTask;
import com.aspire.boc.mms.gwcmp.model.GwcmpProcessTaskExample;
import com.aspire.boc.mms.gwcmp.model.GwcmpTableUpdateInfo;
import com.aspire.boc.mms.gwcmp.model.GwcmpTableUpdateInfoExample;
import com.aspire.boc.mms.gwcmp.util.Constants;
import com.aspire.boc.mms.gwcmp.util.GwcmpAdminUtil;
import com.aspire.boc.mms.wmf.util.Json;
import com.aspire.boc.mms.wmf.util.Page;
import com.aspire.boc.mms.wmf.util.ResourceManager;
/**
 * 黑名单Action
 *
 * @date 2016年1月15日 下午3:51:42 
 * @author 朱广祝
 *
 */
@Controller
public class BlacklistAct {

    private static Log logger = LogFactory.getLog(BlacklistAct.class);
    
    @Autowired
    private GwcmpBlacklistMapper gwcmpBlacklistMapper;
    
    @Autowired
    private GwcmpProcessTaskMapper gwcmpProcessTaskMapper;
    
    @Autowired
    private GwcmpTableUpdateInfoMapper gwcmpTableUpdateInfoMapper;
    
    ResourceManager resourceManager = ResourceManager.getInstance();

    /**
     * 获取黑名单列表
     * @param keyWord
     * @return
     */
    @RequestMapping(value="/blacklist/getBlacklist")
    @ResponseBody
    public Map<String, Object> getBlacklist(
			@RequestParam(value = "start", required = true) Integer start,
            @RequestParam(value = "limit", required = true) Integer limit,
			@RequestParam(value = "mobile", required = false) String mobile,
            HttpServletRequest request, HttpServletResponse response) {
        
        // 返回结果
        Map<String, Object> result = new HashMap<String, Object>();
        String operator = GwcmpAdminUtil.getLoginUserName(request);
        StringBuffer logInfo = new StringBuffer();
		logInfo.append("BlacklistAct >>>>>").append(" operator:").append(operator)
			.append(" url: /blacklist/getBlacklist.do").append(" params: [")
			.append("mobile=").append(mobile).append("] ");    
		logger.info(logInfo.toString());
		List<GwcmpBlacklist> list = null;
		Integer total = 0;
        try {
        	GwcmpBlacklistExample example = new GwcmpBlacklistExample();
        	example.setOrderByClause("LATEST_OPERATE_TIME DESC");
        	GwcmpBlacklistExample.Criteria criteria = example.createCriteria();
        	if (StringUtils.isNotBlank(mobile)) {
                criteria.andMobileLike("%" + mobile + "%");
            }
        	total = gwcmpBlacklistMapper.countByExample(example);
        	if (start != null && limit != null) {
                Page page = new Page(start, limit);
                example.setPage(page);
            }
            list = gwcmpBlacklistMapper.selectByExample(example);
        } catch (Exception e) {
            logger.error(logInfo.toString(), e);
            result.put("list", new ArrayList<GwcmpBlacklist>(0));
            return result;
        }
        if(list == null) new ArrayList<GwcmpBlacklist>(0);
        result.put("list", list);
        result.put("total", total);
	    logger.info("[ getBlacklist: [list = "+list.size()+"]");
        return result;
    }
    
    
    /**
     * 获取黑名单任务列表
     * @param start
     * @return
     */
    @RequestMapping(value="/blacklist/getBlacklistTaskList")
    @ResponseBody
    public Map<String, Object> getBlacklistTaskList(
			@RequestParam(value = "start", required = true) Integer start,
            @RequestParam(value = "limit", required = true) Integer limit,
            HttpServletRequest request, HttpServletResponse response) {
        
        // 返回结果
        Map<String, Object> result = new HashMap<String, Object>();
        String operator = GwcmpAdminUtil.getLoginUserName(request);
        StringBuffer logInfo = new StringBuffer();
		logInfo.append("BlacklistAct >>>>>").append(" operator:").append(operator)
			.append(" url: /blacklist/getBlacklistTaskList.do").append(" params: [")
			.append("start=").append(start).append("] ");    
		logger.info(logInfo.toString());
		List<GwcmpProcessTask> list = null;
		Integer total = 0;
        try {
        	GwcmpProcessTaskExample example = new GwcmpProcessTaskExample();
        	example.setOrderByClause("OPERATE_TIME DESC");
        	GwcmpProcessTaskExample.Criteria criteria = example.createCriteria();
        	criteria.andTaskTypeEqualTo(Constants.TASKTYPE_BALICKLIST);
        	total = gwcmpProcessTaskMapper.countByExample(example);
        	if (start != null && limit != null) {
                Page page = new Page(start, limit);
                example.setPage(page);
            }
            list = gwcmpProcessTaskMapper.selectByExample(example);
        } catch (Exception e) {
            logger.error(logInfo.toString(), e);
            result.put("list", new ArrayList<GwcmpProcessTask>(0));
            return result;
        }
        if(list == null) new ArrayList<GwcmpProcessTask>(0);
        result.put("list", list);
        result.put("total", total);
	    logger.info("[ getBlacklistTaskList: [list = "+list.size()+"]");
        return result;
    }
    
    /**
     * 新增/删除 关键字
     * @param keyWord
     * @return
     */
    @RequestMapping(value="/blacklist/saveBlacklist")
    @ResponseBody
    public Map<String, Object> saveBlacklist(
			@RequestParam(value = "blackItem", required = true) String blackItem,
			@RequestParam(value = "operateType", required = true) String operateType,
            HttpServletRequest request, HttpServletResponse response) {
        
        // 返回结果
        Map<String, Object> result = new HashMap<String, Object>();
        String operator = GwcmpAdminUtil.getLoginUserName(request);
        StringBuffer logInfo = new StringBuffer();
		logInfo.append("BlacklistAct >>>>>").append(" operator:").append(operator)
			.append(" url: /blacklist/saveBlacklist.do").append(" params: [")
			.append("blackItem=").append(blackItem).append(" operateType=").append(operateType).append("] ");    
		logger.info(logInfo.toString());
        try {
        	//判断是否已存在此关键字
        	GwcmpBlacklistExample example = new GwcmpBlacklistExample();
        	GwcmpBlacklistExample.Criteria criteria = example.createCriteria();
            criteria.andMobileEqualTo(blackItem);
        	List<GwcmpBlacklist> list = gwcmpBlacklistMapper.selectByExample(example);
        	//获取具体操作 1 新增 2 删除
        	if("1".equals(operateType)){
        		if(StringUtils.isBlank(blackItem) || !StringUtils.isNumeric(blackItem) || blackItem.length() < 11){
        			result.put("failure", Boolean.TRUE);
                    result.put("msg", "黑名单["+blackItem+"]必须是11位的纯数字！");
                    logger.info("saveBlacklist mobile["+blackItem+"] is not valid!");
                    return result;
        		}
        		//新增
        		if(list != null && list.size() > 0){
            		result.put("failure", Boolean.TRUE);
                    result.put("msg", "黑名单["+blackItem+"]已存在！");
                    logger.info("saveBlacklist mobile["+blackItem+"] exists!");
                    return result;
            	}else{
            		GwcmpBlacklist wcmpBlacklist = new GwcmpBlacklist();
            		wcmpBlacklist.setMobile(blackItem);
            		wcmpBlacklist.setLatestOperateTime(new Date());
            		wcmpBlacklist.setLatestOperator(operator);
            		gwcmpBlacklistMapper.insertSelective(wcmpBlacklist);
            		//更新GWCMP_TABLE_UPDATE_INFO表
            		updateGwcmpTableUpdateInfo();
            		logger.info("saveBlacklist mobile["+blackItem+"] has saved!");
            	}
        	}else if("2".equals(operateType)){
        		//删除
        		if(list != null && list.size() > 0){
        			gwcmpBlacklistMapper.deleteByExample(example);
            		//更新GWCMP_TABLE_UPDATE_INFO表
            		updateGwcmpTableUpdateInfo();
                    logger.info("saveBlacklist mobile["+blackItem+"] has deleted!");
            	}else{
            		result.put("failure", Boolean.TRUE);
                    result.put("msg", "黑名单["+blackItem+"]不存在！");
                    logger.info("saveBlacklist mobile["+blackItem+"] not exists!");
                    return result;
            	}
        	}
        } catch (Exception e) {
            logger.error(logInfo.toString(), e);
            result.put("failure", Boolean.TRUE);
            result.put("msg", "系统异常");
            return result;
        }
        result.put("success", Boolean.TRUE);
        result.put("msg", "黑名单["+blackItem+"]已成功更新！");
	    logger.info("[ saveBlacklist: result : success ]");
        return result;
    }
    
    /**
     * 批量新增/删除 黑名单
     * @param keyWord
     * @return
     */
    @RequestMapping(value="/blacklist/batchSaveBlacklist")
    public ResponseEntity<String> batchSaveBlacklist(
			@RequestParam(value = "blacklistFile", required = true) MultipartFile blacklistFile,
			@RequestParam(value = "operateType", required = true) String operateType,
			@RequestParam(value = "reason", required = false) String reason,
            HttpServletRequest request, HttpServletResponse response) {
        
        // 返回结果
        Map<String, Object> result = new HashMap<String, Object>();
        HttpHeaders httpHeaders = new HttpHeaders();
        MediaType mediaType = new MediaType("text", "html", Charset.forName("utf-8"));
        httpHeaders.setContentType(mediaType);
        String operator = GwcmpAdminUtil.getLoginUserName(request);
        StringBuffer logInfo = new StringBuffer();
		logInfo.append("BlacklistAct >>>>>").append(" operator:").append(operator)
			.append(" url: /blacklist/batchSaveBlacklist.do").append(" params: [")
			.append("blacklistFile=").append(blacklistFile.getOriginalFilename()).append(" operateType=").append(operateType).append("] ");    
		logger.info(logInfo.toString());
        try {
        	//把文件上传到指定路径
        	if (blacklistFile == null || blacklistFile.getSize() == 0) {
				result.put("failure", Boolean.valueOf(true));
				result.put("msg", "文件内容为空！");
				return new ResponseEntity<String>(Json.toJson(result), httpHeaders, HttpStatus.OK);
			}
        	String filePath = resourceManager.getValue("blacklist.upload.path")+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+File.separator;
        	File storeDir = new File(filePath);
        	if(!storeDir.exists()){
        		storeDir.mkdir();
        	}
        	String taskId = UUID.randomUUID().toString();
        	String fileName =  taskId + blacklistFile.getOriginalFilename().substring(
        			blacklistFile.getOriginalFilename().lastIndexOf(
									"."));
        	File uploadFile = new File(filePath,fileName);
        	logger.info("batchSaveKeyword file store:"+filePath+fileName);
        	blacklistFile.transferTo(uploadFile);
        	//更新任务表
        	GwcmpProcessTask gwcmpProcessTask = new GwcmpProcessTask();
        	gwcmpProcessTask.setFilePath(filePath + fileName);
        	gwcmpProcessTask.setId(taskId);
        	gwcmpProcessTask.setOperator(operator);
        	gwcmpProcessTask.setTaskType(Constants.TASKTYPE_BALICKLIST);
        	gwcmpProcessTask.setOperateType(Short.valueOf(operateType));
        	gwcmpProcessTask.setOperateTime(new Date());
        	gwcmpProcessTask.setStatus(Short.valueOf(Constants.uploadStatus.PENDING.ordinal()+""));
        	gwcmpProcessTask.setReason(reason);
        	int uploadFlag = gwcmpProcessTaskMapper.insertSelective(gwcmpProcessTask);
        	if(uploadFlag == 0){
        		result.put("failure", Boolean.TRUE);
                result.put("msg", "创建任务失败！");
                logger.info("[ batchSaveBlacklist: result : fail ]");
                return new ResponseEntity<String>(Json.toJson(result), httpHeaders, HttpStatus.OK);
        	}
        } catch (Exception e) {
            logger.error(logInfo.toString(), e);
            result.put("failure", Boolean.TRUE);
            result.put("msg", "系统异常");
            return new ResponseEntity<String>(Json.toJson(result), httpHeaders, HttpStatus.OK);
        }
        result.put("success", Boolean.TRUE);
	    logger.info("[ batchSaveBlacklist: result : success ]");
	    return new ResponseEntity<String>(Json.toJson(result), httpHeaders, HttpStatus.OK);
    }
    
    private void updateGwcmpTableUpdateInfo(){
    	GwcmpTableUpdateInfo updateInfo = new GwcmpTableUpdateInfo();
    	GwcmpTableUpdateInfoExample example = new GwcmpTableUpdateInfoExample();
    	GwcmpTableUpdateInfoExample.Criteria criteria = example.createCriteria();
    	criteria.andTableNameEqualTo("GWCMP_BLACKLIST");
    	List<GwcmpTableUpdateInfo> list = gwcmpTableUpdateInfoMapper.selectByExample(example);
    	if(list != null && list.size() > 0){
    		//更新GwcmpTableUpdateInfo表
    		updateInfo = list.get(0);
    		updateInfo.setUpdateTime(new Date());
    		gwcmpTableUpdateInfoMapper.updateByPrimaryKey(updateInfo);
    		logger.info("updateGwcmpTableUpdateInfo GWCMP_BLACKLIST update!");
    	} else {
    		//插入数据
    		updateInfo.setTableName("GWCMP_BLACKLIST");
    		updateInfo.setUpdateTime(new Date());
    		gwcmpTableUpdateInfoMapper.insertSelective(updateInfo);
    		logger.info("updateGwcmpTableUpdateInfo GWCMP_BLACKLIST insert!");
    	}
    }
    
}
